package com.jjiang.bbmall.ware.listener;

import com.jjiang.bbmall.ware.service.WareSkuService;
import com.jjiang.common.to.OrderTo;
import com.jjiang.common.to.mq.StockLockedTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁；本实现为下单成功，但是后续报错的回滚【库存工作单还存在】
     * 必须要手动确认，以便与重试
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息:" + to.getId().toString());
        Boolean retry = true;
        try {
            retry = wareSkuService.unlockStock(to);
        } catch (Exception e) {
            // 有异常，消费失败，需要重试
        }
        if (retry) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭的消息:" + to.getOrderSn());
        Boolean retry = true;
        try {
            retry = wareSkuService.unlockStock(to);
        } catch (Exception e) {
            // 有异常，消费失败，需要重试
        }
        if (retry) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
